import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sjx/common_ui/smart_refresh/smart_refresh_widget.dart';
import 'package:sjx/common_ui/web/webview_page.dart';
import 'package:sjx/common_ui/web/webview_widget.dart';
import 'package:sjx/pages/home/banner/home_banner_widget.dart';
import 'package:sjx/pages/home/home_vm.dart';
import 'package:sjx/repository/model/home_list_model.dart';
import 'package:sjx/route/route_utils.dart';
import 'package:sjx/route/routes.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  HomeViewModel model = HomeViewModel();
  BannerController? bannerController = BannerController();
  late RefreshController _refreshController;

  @override
  void initState() {
    _refreshController = RefreshController(initialRefresh: false);
    super.initState();
    model.initDataList(false);
  }

  void refreshOrLoad(bool loadMore) {
    model.initDataList(loadMore, complete: (loadMore) {
      if (loadMore) {
        _refreshController.loadComplete();
      } else {
        _refreshController.refreshCompleted();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return model;
      },
      builder: (BuildContext context, Widget? child) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: SafeArea(
            child: SmartRefreshWidget(
              controller: _refreshController,
              onLoading: () {
                refreshOrLoad(true);
              },
              onRefresh: () {
                refreshOrLoad(false);
              },
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    BannerWidget(
                      controller: bannerController,
                      itemClick: (title, url) {
                        RouteUtils.push(
                          context,
                          WebViewPage(
                            loadResource: url,
                            webViewType: WebViewType.URL,
                            showTitle: true,
                            title: title,
                          ),
                        );
                      },
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        left: 20.w,
                        top: 10.h,
                        right: 20.w,
                        bottom: 10.h,
                      ),
                      child: Row(
                        children: [
                          SizedBox(
                            height: 20.h,
                            width: 4.w,
                            child: DecoratedBox(
                              decoration: BoxDecoration(
                                color: Theme.of(context).colorScheme.primary,
                                borderRadius: BorderRadius.circular(1),
                              ),
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Text(
                            "推荐任务",
                            style: TextStyle(
                              fontSize: 18.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.black87,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Consumer<HomeViewModel>(
                      builder: (context, value, child) {
                        return ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: value.listData?.length ?? 0,
                          itemBuilder: (BuildContext context, int index) {
                            HomeListItemData? item = value.listData?[index];
                            return _listItem(item: item, onItemClick: () {
                              RouteUtils.pushForNamed(context, RoutePath.task_detail, arguments: item?.taskNo);
                            });
                          },
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  //列表
  Widget _listItem({HomeListItemData? item, GestureTapCallback? onItemClick}) {
    return Column(
      children: [
        GestureDetector(
          onTap: onItemClick,
          child: Container(
            margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 8.h, bottom: 8.h),
            width: double.infinity,
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(8.r)),
                  child: CachedNetworkImage(
                    fit: BoxFit.cover,
                    placeholder: (context, url) {
                      return const Center(child: CircularProgressIndicator());
                    },
                    errorWidget: (context, url, error) {
                      return Image.asset(
                        'assets/images/header.png',
                        width: 48.r,
                        height: 48.r,
                        fit: BoxFit.cover,
                      );
                    },
                    imageUrl: item!.taskThumb,
                    width: 48.r,
                    height: 48.r,
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: 12.w),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Expanded(
                              child: Text(
                                item.taskTitle,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.black87,
                                ),
                              ),
                            ),
                            Text(
                              item.rewardAmountDisplay,
                              style: TextStyle(
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w600,
                                color: Theme.of(context).colorScheme.primary,
                              ),
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            if (item.typeAndTagIcons.isNotEmpty)
                              Row(
                                children: item.typeAndTagIcons.map((icon) {
                                  return Padding(
                                    padding: EdgeInsets.only(right: 4.w), // 图片间距
                                    child: CachedNetworkImage(
                                      imageUrl: icon.imageUrl,
                                      width: icon.width.w,
                                      // 使用数据中的宽度或默认29
                                      height: 16.w,
                                      // 保持比例
                                      fit: BoxFit.contain,
                                      placeholder: (context, url) => SizedBox(
                                        width: icon.width.w,
                                        height: 16.w,
                                      ),
                                      errorWidget: (context, url, error) =>
                                          Icon(Icons.error, size: 16.w),
                                    ),
                                  );
                                }).toList(),
                              ),
                            Text(
                              "${item.approvedUserCount}人已赚 | 剩余${item.leftBidTime}份",
                              style: TextStyle(
                                fontSize: 11.sp,
                                fontWeight: FontWeight.w600,
                                color: Colors.grey,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        Divider(
          height: 5.h,
          thickness: 0.5.h,
          color: Colors.grey[300],
          indent: 20.w,  // 左侧缩进（与内容对齐）
          endIndent: 20.w,  // 右侧缩进
        ),
      ],
    );
  }
}
